import type {  AxiosError } from 'axios'
import { showNotify, closeToast  } from 'vant'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
NProgress.configure({ showSpinner: true })
import { STORAGE_PRINTER_KEY } from "@/stores/mutation-type";
import axios from "axios";
import { localStorage } from "@/utils/local-storage";
// import { useI18n } from "vue-i18n";
// const { t } = useI18n();
// import { useI18n } from "vue-i18n";
// const { t } = useI18n();

declare module 'axios' {
  interface AxiosRequestConfig {
      urlParams?: Record<string, string>;
  }
}

const request = axios.create({
    // API 请求的默认前缀
    baseURL: process.env.VUE_APP_API_BASE_URL_PRINT,
    timeout: 6000,
    headers: {
      // "authorization": "Basic cHJpbnQ6ZTMwNWM5ZjA3ZTlhMDg2MzViYzM5NmEzMzE4MzFjYmM=",
      authorization: "Basic " + btoa("ru:DDgYhQ9Dyx5gXT0CNRoF2AURyeXrmjA1"),
    },
  });
  export type RequestError = AxiosError<{
    message?: string,
    result?: any,
    errorMessage?: string
  }>
  // 异常拦截处理器
const errorHandler = (error: RequestError): Promise<any> => {
    NProgress.done()
    closeToast()
    // console.error('['+error.config.baseURL+error.config.url+'] error:',error)
    if (error.response) {
      const { data = {}, status, statusText } = error.response
      // 403 无权限
      if (status === 403) {
        showNotify({
          type: 'danger',
          message: (data && data.message) || statusText
        })
      }
      // 401 未登录/未授权
      if (status === 401 && data.result && data.result.isLogin) {
        showNotify({
          type: 'danger',
          message: 'Authorization verification failed'
        })
        // 如果你需要直接跳转登录页面
        // location.replace(loginRoutePath)
      }
      // 404
      if (status === 404) {
        showNotify({
          type: 'danger',
          message: error.config.baseURL+error.config.url+': Not Found,Request failed with status code 404'
        })
      }
    }
    if(error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1){
      showNotify({
        type: 'danger',
        message:  error.config.baseURL+error.config.url+': Request timeout'
      })
    }
    if(error.code === "ERR_NETWORK" && error.message.indexOf('Network Error') !== -1){
      showNotify({
        type: 'danger',
        message:  error.config.baseURL+error.config.url+': Network Error'
      })
    }


    return Promise.reject(error)
  }

  request.interceptors.response.use(null, errorHandler)



export const getPrinter = (success, fail) => {
  request.get("/status/printers").then((res) => {
    if (res.status == 200) {
      success(res);
    } else {
      fail(res);
    }
  });
};
export  const printUrl = async (url, success, fail, failPrinter, onfinally) => {
  const printerCode = localStorage.get(STORAGE_PRINTER_KEY);
  if (printerCode == null) {
    failPrinter();
    return;
  }

  request({
    url: "/push/url",
    method: 'post',
    params: {
      printerCode: printerCode,
      url: url
    }
  })
    .then((res) => {
      if (res.status == 200) {
        // success(res);
        if(res.data.status=='error'){
          fail(res['data']["message"]);
        }else{
          success(res);
        }
      } else {
        fail(res['data']["message"]);
      }
    }).finally(onfinally);


};


